<?php

namespace services\models;

use services\sms\SmsSend;
use Yii;
use \yii\helpers\ArrayHelper;

/**
 * This is the model class for table "iliketry.member_info".
 *
 * @property integer $no
 * @property integer $member_no
 * @property string $username
 * @property string $true_name
 * @property string $area
 * @property string $ceng
 * @property string $code
 * @property string $cell
 * @property string $call
 * @property string $add_time
 * @property string $email
 * @property string $have_check
 * @property integer $cell_jh_num
 * @property string $shi
 * @property string $lou
 * @property string $company
 * @property integer $status
 * @property integer $father_member_no
 * @property integer $vip_last_month
 * @property string $is_forbid
 * @property string $school
 * @property integer $city_no
 * @property integer $area_no
 * @property integer $district_no
 * @property string $yx
 * @property string $outsite
 * @property integer $yc
 * @property integer $apply_count
 * @property integer $old_member_activate_time
 * @property integer $province_no
 * @property integer $province_home_no
 * @property integer $city_home_no
 * @property integer $area_home_no
 * @property integer $district_home_no
 * @property string $home_num
 * @property string $home_room
 * @property string $home_ceng
 * @property integer $cuxiaodx_flag
 * @property integer $confirm_user
 * @property integer $gender
 * @property integer $birthyear
 * @property integer $birthmonth
 * @property integer $birthday
 * @property integer $cuxiaoemail_flag
 * @property integer $xiaohaoflag
 * @property integer $register_type
 * @property integer $article_pass_rate
 * @property integer $last_auth_time
 * @property integer $xt_province_no
 * @property integer $xt_city_no
 * @property integer $xt_area_no
 * @property integer $xt_district_no
 * @property string $xt_lou
 * @property string $xt_shi
 * @property string $xt_ceng
 */
class MemberInfo extends \common\models\MemberInfo
{
    private $_score = null;

    public $memberInfoBestry = null;
    public $member_info_uid = null;


    public function getMoney()
    {
        if ($this->memberInfoBestry === null) {
            $this->memberInfoBestry = MemberInfoBestry::findOne(['lkt_uid' => $this->member_no]);
        }
        return (float)$this->memberInfoBestry->member_money;
    }


    /**
     *
     * get bestry member uid
     * @return int
     */
    public function getMember_uid()
    {
        if ($this->memberInfoBestry === null) {
            $this->memberInfoBestry = MemberInfoBestry::findOne(['lkt_uid' => $this->member_no]);
        }
        return (int)$this->memberInfoBestry->uid;
    }


    public function getMemberInfoBestry()
    {
        return $this->hasOne(MemberInfoBestry::className(), ['lkt_uid' => member_no]);
    }

    /**
     * 检测手机号是否绑定
     * @return bool
     */
    public function checkCell()
    {
        if (empty($this->cell_jh_num) || empty($this->cell)) {
            return false;
        }
        return true;
    }


    /**
     * 获取用户信息
     * @param unknown $params
     * @return \services\models\MemberInfo|NULL
     */
    public static function getMemberInfo($params)
    {
        return self::findOne($params);
    }


    /**
     * 通过免费uid获取会员头像
     * @param int $member_no 免费试用$member_no
     * @param boolean false 是喜试uid true是优选uid
     * @param string $size
     */
    public static function getAvatarByMemberId($member_no, $is_bestry = false, $size = 'middle')
    {
        if ($is_bestry) {
            $info = MemberInfoBestry::find()->select(['uid', 'lkt_uid'])->where(['uid' => $member_no])->one();
            if (!empty($info->lkt_uid)) {
                $member_no = $info->lkt_uid;
            }
        }
        
        $uc_api = Yii::$app->params['api_headimg_url'];//头像接口地址
        $size = in_array($size, array('big', 'middle', 'small')) ? $size : 'middle';
        $member_no = abs(intval($member_no));
        $member_no = sprintf("%09d", $member_no);
        $dir1 = substr($member_no, 0, 3);
        $dir2 = substr($member_no, 3, 2);
        $dir3 = substr($member_no, 5, 2);
        $user_hade = 'src="' . $uc_api . '/data/avatar/' . $dir1 . '/' . $dir2 . '/' . $dir3 . '/' . substr($member_no, -2) . "_avatar_$size.jpg\"";
        $default_head = "onerror=\"this.src='" . $uc_api . "/images/noavatar_" . $size . ".gif'\"";
        return $user_hade . " " . $default_head;

    }

    /**
     * 根据会员id获取会员名称
     * @param int $member_no
     */
    public static function getUserNameByMemberId($member_no)
    {
        return Yii::$app->redis_old->hget('M_' . $member_no, 'username');
        /*
        return ['username'=>'username'];
        $info = self::find()->select('member_no,username')->where(['member_no'=>$member_no])->one();
        if($info === null) {
            return ['username'=>'有试吗'];
        }else {
            return $info;
        }*/
    }

    /**
     * @param $member_no
     * @return null|MemberInfo
     */
    public static function cache($member_no)
    {
        return \services\models\cache\MemberInfo::get($member_no);
    }

    public function cellConfirm()
    {
        if ($this->cell && $this->cell_jh_num) {
            return true;
        }
        return false;
    }

    public function getScore()
    {
        if ($this->_score === null)
            return $this->_score = (int)MemberScore::getScore($this->member_no);
        return $this->_score;
    }

    public static function getCellCode($cell){
        return substr(hexdec(substr(md5($cell . 'sd1212@JDSjj'.date('Ymd')), 10, 10)), 0, 6);
    }

    public function cellConfirmProc($cell, $code = '')
    {
        if (!preg_match('/^1\d{10}$/', $cell)) {
            $this->addError('cell', "手机号错误，请核对后重新输入!");
            return false;
        }
        $originCode = static::getCellCode($cell);

        if (!empty(MemberInfo::find()->where(['cell' => $cell])->andFilterWhere(['>', 'cell_jh_num', '0'])->one())) {
            $this->addError('cell', "该号码已绑定!");
            return false;
        }

        if ($code == '') {

            // 新通道发送短信
            $message = "欢迎您成为有试吗会员.您的手机验证码为： " . $originCode . ",请尽快登陆激活";

            $myMSM = SmsSend::factory();
            //以下短信发送未测试
            if ($myMSM->send($cell, $message)) {
                return true;
            } else {
                $this->addError('cell', "发送失败，请不要频繁点击发送且保持手机畅通!");
                return false;
            }

        } else {

            if ($code != $originCode) {
                $this->addError('cell', "请输入正确的验证码!");
                return false;
            }

            // 1如果是第一次验证，加50试豆；
            if ($this->cell_jh_num == 0) {
                MemberScore::addScore(50, "手机激活", $this->member_no);
            }
            $this->cell = $cell;
            $this->cell_jh_num += 1;
            if (!$this->save()) {

                return false;
            }


            // 3如果这个手机是别人介绍过来的，介绍过来的会员加500试豆；
            /*if ($this->cell_jh_num == 1 && $this->father_member_no > 0) {
                MemberScore::addScore(500, "介绍朋友加入有试吗成功", $this->father_member_no);
                Messages::addMessage(0,
                    $this->father_member_no,
                    '系统消息',
                    "您的好友 " . $this->username . " 已验证手机，您获得500试豆奖励，试豆已入账。<br>邀请更多好友，将获得更多试豆奖励~"
                    , 2
                );
            }*/

            //手机号来源
            /*$arr = array();
            $arr['uid'] = $this->member_no;
            $arr['cell'] = $cell;
            $arr['type'] = $_SERVER['HTTP_REFERER'];
            $arr['add_time'] = date('Y-m-d H:i:s');
            $this->db->addRow('minisite.cell', $arr);*/

            // 通知验证成功
            if ($this->cell_jh_num == 1) {
                $this->addError('cell', '手机激活成功，您已经成功获取50试豆奖励!');
                return true;

            } else {
                $this->addError('cell', '手机激活成功!');
                return true;
            }

        }
    }

    public function afterSave($insert, $changedAttributes)
    {
        if (parent::beforeSave($insert)) {
            $redis = Yii::$app->redis_old;
            $redis->hmset("M_" . $this->member_no, ArrayHelper::toArray($this));

        }
        parent::afterSave($insert, $changedAttributes);
    }

}
